import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

import '../../../../hj_model/video_model.dart';
import '../../../hj_model/home/video_list_resp.dart';

// enum ShortVIdeoType {
//   follow,
//   find,
// }

class ShortFindTableView extends StatefulWidget {
  final TagsBean? model;

  ShortFindTableView({this.model});

  @override
  State<StatefulWidget> createState() {
    return _ShortFindTableViewState();
  }
}

class _ShortFindTableViewState extends State<ShortFindTableView> {
  List<VideoModel>? dataArr;
  int currentPage = 1;
  RefreshController? refreshController;
  static Map<String, LocalVideCache> _localCache = {};

  String get cacheKey {
    return "short_find_${widget.model?.name}${widget.model?.id}";
  }

  ////  1-最新 2-最热  5指定tag
  int get typeValue {
    if (widget.model?.name == "最热") {
      return 1;
    }
    if (widget.model?.name == "最新") {
      return 2;
    }
    return 5;
  }

  @override
  void initState() {
    super.initState();
    LocalVideCache? cacheData = _localCache[cacheKey];
    if (cacheData?.dataArr?.isNotEmpty == true) {
      dataArr = cacheData?.dataArr;
      currentPage = cacheData?.page ?? 1;
    } else {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        _loadData();
      });
    }
  }

  void _loadData({int page = 1, int size = 10}) async {
    try {
      VideoListResp? retModel = await VidService.shortFindTabList(page, size, tagID: widget.model?.id, type: typeValue);
      currentPage = page;
      dataArr ??= [];
      if (page == 1) {
        dataArr?.clear();
      }
      dataArr?.addAll(retModel?.videos ?? []);
      _localCache[cacheKey] = LocalVideCache(dataArr: dataArr, page: page);
      if (retModel?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      dataArr ??= [];
      refreshController?.loadComplete();
      debugLog(e);
    }
    refreshController?.refreshCompleted();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (dataArr == null) {
      return LoadingCenterWidget();
    } else if (dataArr!.isEmpty) {
      return CErrorWidget(
        retryOnTap: () {
          dataArr = null;
          setState(() {});
          _loadData();
        },
      );
    } else {
      return pullYsRefresh(
        onLoading: (refreshController) {
          _loadData(page: currentPage + 1);
        },
        onRefresh: (refreshController) {
          _loadData();
        },
        onInit: (ctr) => refreshController = ctr,
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(12, 0, 12, 0),
              sliver: SliverWaterfallFlow(
                gridDelegate: const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 6,
                  mainAxisSpacing: 10,
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext c, int index) {
                    VideoModel videoModel = dataArr![index];
                    var ratio = 168 / 266; // 191/254
                    // if (videoModel.ratio is double && videoModel.ratio != 0) {
                    //   ratio = videoModel.ratio!;
                    // }
                    return VideoSimpleCellWidget(
                      videoModel: videoModel,
                      imgAspectRatio: ratio,
                      textLines: 1,
                      onTap: () {
                        if (videoModel.isRandomAd() == true) {
                          pushToPageByLink(videoModel.randomAdsInfo?.href, id: videoModel.randomAdsInfo?.id);
                        } else {
                          pushToVideoPage(videoModel: videoModel, videoArr: dataArr);
                        }
                      },
                    );
                  },
                  childCount: dataArr?.length ?? 0,
                ),
              ),
            ),
          ],
        ),
      );
    }
  }
}
